import tensorflow as tf
from tensorflow import keras
from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import train_test_split

dataset = fetch_california_housing()
train_x, test_x, train_y, test_y = train_test_split(dataset.data,dataset.target,test_size=0.2,random_state=42)

model = keras.Sequential([
    keras.layers.Dense(16,activation='relu',input_shape = train_x.shape[1:]),
    keras.layers.Dense(1)
])

# 自定义损失函数 
# reduce有降维的意思 因为前面平方得到的是一个矩阵 求均值时是求一个矩阵的均值 得到一个数
def customized_loss(y_true,y_pred):
    return tf.reduce_mean(tf.square(y_pred-y_true))

model.compile( 
    optimizer = keras.optimizers.Adam(0.001),
    loss = customized_loss,
    metrics = ['mse']
)

model.fit(train_x, train_y, epochs=10)

